package com.xs.tool;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;

@Slf4j
public class NetworkUtil {
    public static IpInfo getPublicIp() {
        // 备用服务列表
        String[] services = {
                "https://icanhazip.com",
                "https://ident.me"
        };

        String publicIp = null;
        for (String service : services) {
            try {
                URL url = URI.create(service).toURL();
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(url.openStream()))) {
                    String ip = reader.readLine();
                    if (ip != null && !ip.isEmpty()) {
                        publicIp = ip.trim();
                        break;
                    }
                }
            } catch (Exception e) {
                log.warn("Failed to get public IP from {}: {}", service, e.getMessage());
            }
        }

        // 获取局域网IP
        String localIp;
        try {
            localIp = java.net.InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e) {
            log.error("Failed to get local IP address", e);
            localIp = "127.0.0.1";
        }

        // 如果公网IP获取失败，使用局域网IP作为兜底
        if (publicIp == null || publicIp.isEmpty()) {
            publicIp = localIp;
        }

        return new IpInfo(localIp, publicIp);
    }

    public record IpInfo(String lan, String publicNetwork) { }
}
